<?php
class QAsController extends CController {
	public $defaultAction = 'list';

	public function actions() {
		return array(
			// Captcha action renders the CAPTCHA image
			'captcha' => array(
				'class' => 'CCaptchaAction',
				'backColor' => 0xF5F5F5,
				'foreColor' => 0x6C8D00,
				'maxLength' => 5,
				'minLength' => 5,
				'height' => 30
			)
		);
	}
	
	public function actionList() {
		$errors = array();
		// Dealing with the submission of a new Q&A
		if(isPost() && $_POST['QAs']) {
			if(Users::isLogin()) {
				$_qA = new QAs;
				$_qA->scenario = 'postNewTopic';
				$_qA->attributes = $_POST['QAs'];
				$_qA->qaStatus = QAs::STATUS_UNSOLVED;
				$_qA->qaAuthor = Yii::app()->user->id;
				$_qA->qaIp = $_SERVER['REMOTE_ADDR'];
				$_qA->qaParent = QAs::PARENT_TOPIC;
				$_qA->verifyCode = $_POST['QAs']['verifyCode'];
				$_qA->qaDate = time();
				$_qA->save();
				$errors = $_qA->getErrors();
			} else {
				Yii::app()->user->loginRequired();
			}
		}
		
		// List Q&As according to Q&A's status
		$status = isset($_GET['status']) ? (int)$_GET['status'] : -1;
		if($status === QAs::STATUS_SOLVED) {
			$filter = 'solved';
		} else if($status === QAs::STATUS_UNSOLVED) {
			$filter = 'unsolved';
		} else {
			$filter = 'all';
		}
		
		$criteria = QAs::model()->topic()->$filter()->getDbCriteria();
		$with = array('author');
		$count = QAs::model()->with($with)->count($criteria);
		// Pagination
		$pages = new CPagination($count);
		$pages->pageSize = Yii::app()->params['qAsPerPage'];
		$pages->applyLimit($criteria);
		// Get rows
		$qAs = QAs::model()->desc()->with($with)->findAll($criteria);

		$qA = new QAs;
		// Render to view
		$this->setPageTitle('在线问吧 - 广州心理咨询网');
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/qAsList.js', CClientScript::POS_END);
		// If there is an error or more, jump to post Q&A's anchor
		if(count($errors) > 0) {
			Yii::app()->clientScript->registerScript('jump2Post', 'window.location.hash = "postQA";', CClientScript::POS_END);
		}
		$this->render('qAsList', array(
			'qAs' => $qAs,
			'qA' => $qA,
			'errors' => $errors,
			'filter' => $filter,
			'pages' => $pages
		));
	}
	
	public function actionSearch() {
		if(isset($_GET['key'])) {
			$key = trim(urldecode($_GET['key']));
			$errors = array();
			if(strlen($key) <= 3) {
				$errors[] = '您输入的搜索关键字过短，请重新输入。';
			}
			if( ! sizeof($errors) > 0) {
				$criteria = new CDbCriteria;
				$criteria->order = 'qaId DESC';
				$criteria->addCondition('qaParent = '.QAs::PARENT_TOPIC, 'AND')
					->addSearchCondition('qaTitle', $key, true, 'OR')
					->addSearchCondition('qaContent', $key, true, 'AND');
				// Get the count of all posts
				$qAsCount = QAs::model()->count($criteria);
				// Pagination
				$pages = new CPagination($qAsCount);
				$pages->pageSize = 10;
				$pages->params = array('key' => urlencode($key));
				$pages->applyLimit($criteria);
				// Posts' data
				$qAs = QAs::model()->findAll($criteria);
			}
			$qA = new QAs;
			$this->setPageTitle('广州心理咨询网 - 在线问吧');
		
			$this->render('search', array(
				'qAs' => isset($qAs) ? $qAs : array(),
				'pages' => isset($pages) ? $pages : new CPagination(0),
				'qA' => isset($qA) ? $qA : new QAs,
				'key' => htmlspecialchars($key),
				'errors' => $errors
			));
		}
	}
	
	public function actionView() {
		$qa = $this->loadQa();
	
		if(isPost()) {
			if($qa->canReply() && $qa->qaStatus == QAs::STATUS_UNSOLVED) {
				$reply = new QAs;
				$reply->qaParent = $qa->qaId;
				$reply->attributes = $_POST['QAs'];
				$reply->qaTitle = $reply->qaTitle;
				$reply->qaContent = $reply->qaContent;
				$reply->qaStatus = QAs::STATUS_REPLY;
				$reply->qaAuthor = Users::isLogin();
				$reply->qaIp = $_SERVER['REMOTE_ADDR'];
				$reply->qaDate = time();
				if($reply->save() && $reply->author->getIsAdmin()) {
					sendMail($qa->author->email, $qa->author->userName(), '[广州心理咨询网]您好，'.$qa->author->userName().'，咨询师'.$reply->author->userName().'对您在在线问吧的提问进行了回复', $reply->getNotifyingMailText($qa));
				}
			}
		}

		// Add to history
		QAs::addToHistory($qa->qaId);
		
		$replies = $qa->getReplies();
		
		$this->setPageTitle($qa->qaTitle.' - 广州心理咨询网');
		$this->render('view', array(
				'qa' => $qa,
				'replies' => $replies,
				'_reply' => isset($reply) ? $reply : new QAs
			)
		);
	}
	
	public function actionChangestatus() {
		$qa = $this->loadQa();
		if($qa->qaStatus == QAs::STATUS_UNSOLVED && ForumMembers::isLogin()) {
			if($qa->canReply()) {
				$qa->qaStatus = QAs::STATUS_SOLVED;
				if($qa->save()) {
					Yii::app()->user->setFlash('success', '提问状态设置成功，谢谢您对我们工作的支持！');
					$this->redirect(Yii::app()->request->urlReferrer.'#reply_box');
				}
			}
		}
	}

	protected function loadQa($id = null) {
		if($id !== null || isset($_GET['id']))
			$qa = QAs::model()->findbyPk($id!==null ? $id : $_GET['id']);
		if($qa === null || $qa->qaParent != QAs::PARENT_TOPIC)
			throw new CHttpException(404,'The requested post does not exist.');
		return $qa;
	}
}